﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class SiteWorx_UserMaintenance : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadMembers();
            lblMessage.Text = "";
        }
    }

    private void LoadMembers()
    {
        // first let's clear all contents in all the forms.

        // edit user form.
        lblUserName.Text = "";
        txtFirstName.Text = "";
        txtLastName.Text = "";
        txtEmail.Text = "";
        txtCompany.Text = "";
        txtAddress.Text = "";
        txtCity.Text = "";
        txtZip.Text = "";
        txtPhone.Text = "";
        chkAdministrator.Checked = false;
        chkCustomer.Checked = false;

        // new user form.
        txtNewFirstName.Text = "";
        txtNewLastName.Text = "";
        txtNewEmail.Text = "";
        txtNewCompany.Text = "";
        txtNewAddress.Text = "";
        txtNewCity.Text = "";
        lstNewState.ClearSelection();
        txtNewZip.Text = "";
        txtNewPhoneNumber.Text = "";
        txtPassword.Text = "";
        txtConfirmPassword.Text = "";
        rcboQuestions.ClearSelection();
        txtAnswer.Text = "";
        chkNewAdministrator.Checked = false;
        chkNewCustomer.Checked = false;


        // next we show the correct listing of users.
        pnlUserList.Visible = true;
        pnlUserDetails.Visible = false;
        pnlCreateUser.Visible = false;
        rgvUserList.DataSource = Membership.GetAllUsers();
        rgvUserList.DataBind();
    }

    protected void rgvUserList_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        string userName = ((Label)e.Item.FindControl("lblUserName")).Text;
        Membership.DeleteUser(userName);
        LoadMembers();
    }

    protected void rgvUserList_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            string userName = e.CommandArgument.ToString();
            LoadMember(userName);
        }
    }

    private void LoadMember(string userName)
    {
        pnlUserList.Visible = false;
        pnlUserDetails.Visible = true;
        pnlCreateUser.Visible = false;
        lblMessage.Text = "";
        lblNewMessage.Text = "";

        // Get membership user.
        MembershipUser user = Membership.GetUser(userName);

        // Get user's profile.
        ProfileCommon profileCommon;
        profileCommon = Profile.GetProfile(userName);
             
                
        // Load update form.
        lblUserName.Text = user.UserName;
        txtFirstName.Text = profileCommon.FirstName;
        txtLastName.Text = profileCommon.LastName;
        txtEmail.Text = user.Email;
        txtCompany.Text = profileCommon.Company;
        txtTaxId.Text = profileCommon.TaxId;
        txtAddress.Text = profileCommon.StreetAddress;
        txtCity.Text = profileCommon.City;
        lstState.ClearSelection();
        try
        {
            lstState.Items.FindByValue(profileCommon.State).Selected = true;
        }
        catch { }
        txtZip.Text = profileCommon.Zip;
        txtPhone.Text = profileCommon.Phone;
        chkAdministrator.Checked = Roles.IsUserInRole(user.UserName, "Administrator");
        chkCustomer.Checked = Roles.IsUserInRole(user.UserName, "Customer");
    }

    protected void btnSaveNew_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            MembershipCreateStatus createStatus;
            try
            {
                Membership.CreateUser(txtNewEmail.Text, txtPassword.Text, txtNewEmail.Text, rcboQuestions.SelectedValue,
                                      txtAnswer.Text, true, out createStatus);

            }
            catch (Exception ex)
            {
                lblNewMessage.Text = ex.Message;
                return;
            }

            if (createStatus != MembershipCreateStatus.Success)
            {
                switch (createStatus)
                {
                    case MembershipCreateStatus.DuplicateEmail:
                        lblNewMessage.Text = "Email address already exists.";
                        break;
                    case MembershipCreateStatus.DuplicateUserName:
                        lblNewMessage.Text = "User name already exists.";
                        break;
                    case MembershipCreateStatus.InvalidAnswer:
                        lblNewMessage.Text = "Invalid security answer.";
                        break;
                    case MembershipCreateStatus.InvalidEmail:
                        lblNewMessage.Text = "Invalid email address.";
                        break;
                    case MembershipCreateStatus.InvalidPassword:
                        lblNewMessage.Text = "Invalid password. Password must be greater than 6 characters.";
                        break;
                    case MembershipCreateStatus.InvalidUserName:
                        lblNewMessage.Text = "Invalid user name.";
                        break;
                    default:
                        lblNewMessage.Text = "Unknown error has occured.";
                        break;
                }
                return;
            }

            // Get user's profile.
            ProfileCommon profileCommon;
            profileCommon = Profile.GetProfile(txtNewEmail.Text);

            profileCommon.FirstName = txtNewFirstName.Text;
            profileCommon.LastName = txtNewLastName.Text;
            profileCommon.DisplayName = txtNewFirstName.Text + " " + txtNewLastName.Text;
            profileCommon.Company = txtNewCompany.Text;
            profileCommon.TaxId = txtNewTaxId.Text;
            profileCommon.StreetAddress = txtNewAddress.Text;
            profileCommon.City = txtNewCity.Text;
            profileCommon.State = lstNewState.SelectedValue;
            profileCommon.Zip = txtNewZip.Text;
            profileCommon.Phone = txtNewPhoneNumber.Text;

            try
            {
                profileCommon.Save();
            }
            catch (Exception ex)
            {
                lblNewMessage.Text = ex.Message;
                return;
            }

            // Check for role assignment.
            if (chkNewAdministrator.Checked)
            {
                try
                {
                    string[] userNames = { txtNewEmail.Text };
                    Roles.AddUsersToRole(userNames, "Administrator");
                }
                catch (Exception ex)
                {
                    lblNewMessage.Text = ex.Message;
                    return;
                }
            }

            // Check for role assignment.
            if (chkNewCustomer.Checked)
            {
                try
                {
                    string[] userNames = { txtNewEmail.Text };
                    Roles.AddUsersToRole(userNames, "Customer");
                }
                catch (Exception ex)
                {
                    lblNewMessage.Text = ex.Message;
                    return;
                }
            }
            LoadMembers();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            MembershipUser user = Membership.GetUser(lblUserName.Text);
            user.Email = txtEmail.Text;

            try
            {
                Membership.UpdateUser(user);
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
                return;
            }

            // Get user's profile.
            ProfileCommon profileCommon;
            profileCommon = Profile.GetProfile(lblUserName.Text);

            profileCommon.FirstName = txtFirstName.Text;
            profileCommon.LastName = txtLastName.Text;
            profileCommon.DisplayName = txtFirstName.Text + " " + txtLastName.Text;
            profileCommon.Company = txtCompany.Text;
            profileCommon.TaxId = txtTaxId.Text;
            profileCommon.StreetAddress = txtAddress.Text;
            profileCommon.City = txtCity.Text;
            profileCommon.State = lstState.SelectedValue;
            profileCommon.Zip = txtZip.Text;
            profileCommon.Phone = txtPhone.Text;

            try
            {
                profileCommon.Save();
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
                return;
            }

            // check for role assignment.
            if (chkAdministrator.Checked)
            {
                if (!Roles.IsUserInRole(user.UserName, "Administrator"))
                {
                    try
                    {
                        Roles.AddUserToRole(user.UserName, "Administrator");
                    }
                    catch (Exception ex)
                    {
                        lblMessage.Text = ex.Message;
                        return;
                    }
                }
            }
            else
            {
                if (Roles.IsUserInRole(user.UserName, "Administrator"))
                {
                    try
                    {
                        Roles.RemoveUserFromRole(user.UserName, "Administrator");
                    }
                    catch (Exception ex)
                    {
                        lblMessage.Text = ex.Message;
                        return;
                    }
                }
            }
            if (chkCustomer.Checked)
            {
                if (!Roles.IsUserInRole(user.UserName, "Customer"))
                {
                    try
                    {
                        Roles.AddUserToRole(user.UserName, "Customer");
                    }
                    catch (Exception ex)
                    {
                        lblMessage.Text = ex.Message;
                        return;
                    }
                }
            }
            else
            {
                if (Roles.IsUserInRole(user.UserName, "Customer"))
                {
                    try
                    {
                        Roles.RemoveUserFromRole(user.UserName, "Customer");
                    }
                    catch (Exception ex)
                    {
                        lblMessage.Text = ex.Message;
                        return;
                    }
                }
            }
            LoadMembers();
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        LoadMembers();
    }

    protected void btnCreateNewUser_Click(object sender, EventArgs e)
    {
        pnlUserList.Visible = false;
        pnlUserDetails.Visible = false;
        pnlCreateUser.Visible = true;
        lblMessage.Text = "";
        lblNewMessage.Text = "";
    }

    protected void rgvUserList_PageIndexChanged(object source, Telerik.Web.UI.GridPageChangedEventArgs e)
    {
        LoadMembers();
        rgvUserList.CurrentPageIndex = e.NewPageIndex;
    }
}
